package com.nbwyctf.helper.controller;

import com.google.common.base.Strings;
import com.nbwyctf.helper.pojo.User;
import com.nbwyctf.helper.result.AjaxResult;
import com.nbwyctf.helper.service.AuthService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;

@RequestMapping("auth")
@RestController
public class AuthController {
    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/getCurrentUser")
    public AjaxResult getCurrentUser(HttpServletRequest request){
        User user = AuthService.getCurrentUser(request);
        // 如果用其他身份的用户，只需要在session.setAttribute()设置不同的身份（通过不同身份实体类）
        HashMap<String, Object> data = new HashMap<>(2);
        if (user != null) {
            logger.info("当前用户身份为【用户】，姓名：{}", user.getFullName());
            data.put("user", user);
            data.put("role", "用户");
        } else {
            logger.info("当前用户身份为【未注册】");
        }
        return AjaxResult.ajaxSuccess(data);
    }

    /**
     @RequestMapping("/loginUrl")
    public AjaxResult openIdLoginUrl(HttpServletResponse response, String next) {
        if (Strings.isNullOrEmpty(next)) {
            next = frontendUrl;
        }
        StringBuilder authorize = new StringBuilder(AUTHORIZE_URL);
        authorize.append("&site_id=").append(siteId);
        authorize.append("&redirect_uri=").append("http://hello.world.com:8080").append("/api/auth/login?next=").append(next);
        logger.info("authorize: " + authorize);
        try {
            response.sendRedirect(authorize.toString());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return AjaxResult.ajaxSuccess();
    }
    */

    /**
    @RequestMapping("/login")
    public AjaxResult openIdLogin(HttpServletRequest request, HttpServletResponse response){
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        String next = request.getParameter("next");

        //Check state
        HttpSession session = request.getSession();
        String sessionState = (String) session.getAttribute("state");
        if (!Strings.isNullOrEmpty(state)) {
            if (sessionState == null || !sessionState.equals(state)) {
                logger.info("state不一致, 登录失败!");
                return AjaxResult.ajaxFailed("state不一致, 登录失败!");
            }
        }
        if (code != null) {
            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            params.add("code", code);
            params.add("redirect_uri", "http://exam-local.leihuo.netease.com:8080/api/auth/login?next=" + next);
            params.add("client_id", clientId);
            params.add("client_secret", clientSecret);
            HttpHeaders accessHeaders = new HttpHeaders();
            accessHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
            HttpEntity<MultiValueMap<String, String>> body = new HttpEntity<>(params, accessHeaders);
            ResponseEntity<String> accessTokenEntity = restTemplate.postForEntity(ACCESS_TOKEN_URL, body, String.class);
            if (accessTokenEntity.getStatusCodeValue() == 200) {
                // 设置Json数据下划线转驼峰
                GsonBuilder gsonBuilder = new GsonBuilder();
                gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
                Gson gson = gsonBuilder.create();
                AccessTokenResponse accessTokenResponse = gson.fromJson(accessTokenEntity.getBody(), AccessTokenResponse.class);

                // 接下来是将获取的用户信息进行处理（如查询用户身份）...
//                User userInfo = userMapper.selectByEmail(email);
//                if (userInfo != null){
//                    session.setAttribute("user", userInfo);
//                }

                Cookie cookie = new Cookie("user", idToken);
                cookie.setPath("/");
                cookie.setMaxAge(7 * 24 * 60 * 60);
                cookie.setHttpOnly(false);
                response.addCookie(cookie);

                logger.info(infoBody);
                logger.info("LOGIN SUCCESS");
                try {
                    response.sendRedirect(next);
                    return AjaxResult.ajaxSuccess();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            } else {
                logger.info("error: invalid_request");
                return AjaxResult.ajaxFailed("无效申请");
            }
        }
        logger.info("error: invalid_request");
        return AjaxResult.ajaxFailed("无效申请");
    }
     */

    @RequestMapping("/logout")
    public AjaxResult logout(HttpServletRequest request, HttpServletResponse response) {
        Cookie cookie = new Cookie("user", null);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);

        AuthService.logout(request);

        try {
            response.sendRedirect("");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return AjaxResult.ajaxSuccess("注销成功！");
    }
}
